################################################################################
#### Title: Merging Senders and Message Attributes
#### Portion of the Analysis: Merge the senders data with the message attributes
################################################################################

##########
# Set up #
##########

# Clear global environment 
rm(list=ls())

# Set working directory
setwd("/Users/martinnaunov/Desktop/Desktop - Martin’s MacBook Pro (2)/Persuasion/2_workingdata")


# Load relevant packages 
library(dplyr)
library(stringr)
library(stringi)
library(readxl)

# Read in data on argument characteristics (e.g. personal appeal, use of facts)

df_coded <- read_excel("coded_message_attributes.xlsx")

# Select coded variables and rename them

df_coded <- df_coded %>% 
  dplyr::select(sender_id_s, common_ground, personal_rev, 
                specific_fact) %>% 
  rename(respid = sender_id_s)

# Read in the senders data from the adapted script (senders_cs_v2)
df_senders <- read.csv("senders_w1.csv")

# Combine the message attribute and the senders dataframes
df <- left_join(df_senders, df_coded, by = "respid")

######################
# Message Attributes #
######################

### Message Length in Words ###

# Make a variable called mlengthwords that counts the length of the message in terms 
# of number of words.

df <- df %>%
  mutate(
    writing_task = str_squish(writing_task)
  ) %>%  # Remove unnecessary spaces
  mutate(
    mlengthwords = case_when(
      write_yes == TRUE & !is.na(writing_task) ~ str_count(writing_task, "\\S+"),
      TRUE ~ NA_real_)
  )

### Message Length in Characters ###

df <- df %>%  
  mutate(mlengthchar = case_when(
    write_yes == TRUE & !is.na(writing_task) ~ str_length(writing_task),
    TRUE ~ NA_real_
  ))

##########
# EXPORT #
########## 

# Specify the folder path

folder_path <- "/Users/martinnaunov/Desktop/Desktop - Martin’s MacBook Pro (2)/Persuasion/2_workingdata/"


# Create the full file path including the filename and extension 
file_path <- file.path(folder_path, "senders_working2_v3.csv")

# Export the dataframe to CSV 
write.csv(df, file = file_path, row.names = FALSE)

# Check if file exists 
file.exists(file_path) 
